﻿using System;
using System.Web;

namespace Codemonk.Pease.Server.HttpServer
{
    public abstract class HttpAsyncHandler : IHttpAsyncHandler
    {
        protected abstract IScheduler Scheduler { get; }

        protected abstract IResponsedAsyncResult CreateAsyncResult(HttpContext context, AsyncCallback cb, object extraData);

        public virtual IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var r = CreateAsyncResult(context, cb, extraData);
            Scheduler.AddWorker(r);
            return r;
        }

        public virtual void EndProcessRequest(IAsyncResult r)
        {
            try
            {
                IResponsedAsyncResult result = r as IResponsedAsyncResult;
                result.HttpContext.Response.Write(result.Response);
                result.HttpContext.Response.Flush();
            }
            catch { }
        }

        public virtual bool IsReusable { get { return true; } }

        public virtual void ProcessRequest(HttpContext context) { }
    }
}
